package com.ph.controller.personal.promotion;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ph.constant.ImgConstant;
import com.ph.custom.annotation.MemberCache;
import com.ph.custom.annotation.Token;
import com.ph.custom.cache.CacheContent;
import com.ph.custom.cenum.TokenCheckEnum;
import com.ph.entity.MemberInfo;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.util.date.ThreadLocalDateUtil;
import com.ph.shopping.common.util.oss.OSSClientUtil;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.member.dto.MemberAuthDto;
import com.ph.shopping.facade.member.service.IMemberAuthService;
import com.ph.util.ResultUtil;

/**
 * 
 * @ClassName:  PromotionDivisionController   
 * @Description:推广师    
 * @author: lijie
 * @date:   2017年4月19日 上午10:13:55     
 * @Copyright: 2017
 */
@Controller
@RequestMapping("/personal/promotion")
public class PromotionDivisionController {
	
	private static final Logger logger = LoggerFactory.getLogger(PromotionDivisionController.class);

	@Autowired
	private OSSClientUtil ossClientUtil;
	
	@Reference(version = "1.0.0", retries = 0,timeout = 30000)
	private IMemberAuthService authService;
	/**
	 * 
	 * @Title: loadPromotionAauth   
	 * @Description: 加载推广师认证页面   
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@Token(tokenCache = { TokenCheckEnum.PUT })
	@MemberCache
	@RequestMapping("loadPromotionAauth")
	public String loadPromotionAauth(HttpServletRequest request, Model model, MemberInfo memberInfo,CacheContent<String, String> tokenCache) {
		try {
			Result result = authService.getMemberAuthInfo(memberInfo.getId());
			logger.info("查询推广师认证信息返回数据 result = {}", JSON.toJSONString(result));
			if (result != null && ResultEnum.SUCCESS.getCode().equals(result.getCode())) {
				model.addAttribute("authInfo", result.getData());
			}
			model.addAttribute(tokenCache.getName(), tokenCache.getContent());
		} catch (Exception e) {
			logger.error("加载推广师认证页面错误", e);
		}
		return "promotion/promotionauth";
	}
	/**
	 * 
	 * @Title: promotionAauth   
	 * @Description: 推广师认证   
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@Token(errorDesc = "申请推广师失败")
	@ResponseBody
	@MemberCache
	@RequestMapping("promotionAauthSub")
	public Map<String, Object> promotionAauth(HttpServletRequest request, MemberAuthDto dto, MemberInfo memberInfo) {
		logger.info("推广师申请参数 MemberAuthDto = {}", JSON.toJSONString(dto));
		Map<String, Object> map = ResultUtil.setResult(false, "推广师申请失败");
		try {
			dto.setMemberID(memberInfo.getId());
			Result result = authService.apply(dto);
			logger.info("推广师申请返回数据 result = {}", JSON.toJSONString(result));
			if (result != null) {
				String code = result.getCode();
				if (ResultEnum.SUCCESS.getCode().equals(code)) {
					ResultUtil.setResult(map, true, "推广师申请成功");
				} else if (ResultEnum.MEMBERAUTH_EXIST.getCode().equals(code)) {
					ResultUtil.setResult(map, false, "该会员已是推广师");
				} else if (ResultEnum.ACCOUNT_EXIST.getCode().equals(code)) {
					ResultUtil.setResult(map, false, "账号已经被绑定推广师");
				} else if (ResultEnum.ACCOUNT_VILIDATE_ERROR.getCode().equals(code)) {
					ResultUtil.setResult(map, false, "账号必须为本地电商或新业态");
				}
			}
		} catch (Exception e) {
			logger.error("推广师申请错误", e);
		}
		return map;
	}
	/**
	 * 
	 * @Title: uploadPromotionCer   
	 * @Description: 上传图片   
	 * @param: @param urlfile
	 * @param: @param module
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@RequestMapping("uploadImage")
	@ResponseBody
	public Map<String, Object> uploadImage(MultipartFile uploadImg, String module) {
		Map<String, Object> map = ResultUtil.setResult(false, "图片上传失败");
		try {
			if (StringUtils.isBlank(module)) {
				module = "default";
			}
			if (uploadImg != null) {
				long size = uploadImg.getSize();
				if(size > ImgConstant.MAX_SISE){
					ResultUtil.setResult(false, "图片不能超过5M");
					return map;
				}
				Date createTime = new Date();
				String fileName = uploadImg.getOriginalFilename();
				boolean isFile = StringUtils.endsWithAny(StringUtils.lowerCase(fileName),
						new String[] { ".png", ".jpg", ".jpeg", ".bmp", ".gif" });
				if (isFile) {
					StringBuilder sbud = new StringBuilder();
					sbud.append(module).append("/")
					.append(ThreadLocalDateUtil.dateToString("yyyyMMdd", createTime))
					.append("/").append(ThreadLocalDateUtil.dateToString("yyyyMMddHHmmssSSS", createTime))
					.append(RandomStringUtils.randomNumeric(6)).append(".")
					.append(fileName.substring(fileName.lastIndexOf(".") + ".".length()));
					String filePath = sbud.toString();
					logger.info("图片上传参数 upload data :" + filePath);
					Object result = ossClientUtil.putObject(filePath, uploadImg);
					logger.info("图片上传返回数据：result = {}",JSON.toJSONString(result));
					if(result != null){
						map.put("url", result);
						ResultUtil.setResult(map, true, "图片上传成功");
					}
				}
			}
		} catch (Exception e) {
			logger.error("图片上传错误", e);
		}
		return map;
	}
}
